<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="../include/laypublic.jsp" %>
<%@ include file="../include/vueComponent.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <title>其他补充协议</title>
</head>
<style>
    .unit_img div {
        height: 41px;
    }
</style>
<link rel="stylesheet" href="${ctx}/resources/vue-element-lib/detail.css">
<body>
<div id="app">
    <div class="layui-tab layui-tab-brief" lay-filter="xqxx-tab-all">
        <ul class="layui-tab-title">
            <li id="tbglId" class="layui-this" lay-id="0">其他补充协议</li>
            <li id="zgysId" lay-id="1">历史审批信息</li>
        </ul>
        <div class="layui-tab-right">
            <%--            <c:if test="${isAuditFlag eq '1'}">--%>
            <template v-if="layId==0">
                <button type="button" class="layui-btn layui-btn-primary layui-btn-radius" @click="save(0)">保存
                </button>
                <button type="button" class="layui-btn layui-btn-radius" @click="save(1)">提交</button>
            </template>
            <%--            </c:if>--%>
            <c:if test="${auditTabFlag eq '1'}">
                <button type="button" class="layui-btn layui-btn-primary layui-btn-radius" @click="audit(0)">
                    不同意
                </button>
                <button type="button" class="layui-btn layui-btn-radius" @click="audit(1)">同意</button>
            </c:if>
        </div>
        <div class="layui-tab-content" style="height: 100px;">
            <div class="layui-tab-item layui-show">
                <div class="container">
                    <el-form ref="formRef" label-width="180px" label-suffix="："
                             label-position="left">

                        <div class="title">
                            <h3>项目基础信息</h3>
                        </div>
                        <el-row>
                            <x-col>
                                <el-form-item label="项目名称">
                                    <span>{{basic.proName}}</span>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="项目编码">
                                    <span>{{basic.proCode}}</span>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="申请公司">
                                    <span>{{basic.compName}}</span>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="申请部门">
                                    <span>{{basic.deptName}}</span>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="申请人">
                                    <span>{{basic.staffName}}</span>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="区域公司">
                                    <span>{{basic.compName}}</span>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="项目公司">
                                    <span>{{basic.compName}}</span>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="实施机构">
                                    <span>{{basic.compName}}</span>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="项目负责人">
                                    <x-input name="项目负责人" v-model="basic.projectLeader"></x-input>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="项目地址">
                                    <span>{{basic.cityName}}</span>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <div class="title">
                            <h3>合同评审信息</h3>
                        </div>
                        <el-row>
                            <x-col>
                                <el-form-item label="补充协议名称">
                                    <x-input name="补充协议名称" v-model="info.contractName"></x-input>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="公司名称">
                                    <el-select v-model="info.companyName" placeholder="请选择公司名称" filterable
                                               style="width: 100%;">
                                        <el-option v-for="item in companyList" :key="item.SGUID" :label="item.COOP_NAME"
                                                   :value="item.SGUID">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="协议签订日期">
                                    <el-date-picker style="width: 100%" type="date" value-format="yyyy-MM-dd"
                                                    v-model="info.signAgreementTime"
                                                    placeholder="协议签订日期"></el-date-picker>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="补充协议编码">
                                    <x-input name="补充协议编码" v-model="info.supplementaryAgreementCode"></x-input>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col position="full">
                                <el-form-item label="补充内容说明">
                                    <x-input type="textarea" :rows="4" name="补充内容说明"
                                             v-model="info.supplementContent"></x-input>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="费用类型">
                                    <x-select name="费用类型" v-model="info.costTypes" disabled
                                              :options="costTypesEnumList"></x-select>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <div class="title">
                            <h3>项目代付费信息</h3>
                        </div>
                        <div class="unit">
                            <div class="unit_add">
                                <button class="layui-btn layuiadmin-btn-admin" type="button" data-type="add"
                                        @click="add">
                                    <i class="layui-icon layui-icon-add-1 layuiadmin-button-btn"></i>添加子项
                                </button>
                            </div>
                            <div class="unit_center">
                                <div class="unit_img">
                                    <template v-for="(item,index) in projectAgencyPaymentList">
                                        <div class="item" :key="index" v-if="item.rowspan"
                                             :style="{height:(item.rowspan*41)+'px',lineHeight:(item.rowspan*41)+'px'}">
                                            <img src="${ctx}/resources/images/del.png" alt="" v-if="item.add"
                                                 @click="del(item.itemType)">
                                        </div>
                                    </template>

                                </div>
                                <el-table :data="projectAgencyPaymentList" style="width: 100%" border
                                          :span-method="objectSpanMethod" ref="tableRef">
                                    <el-table-column label="子项名称" align="center">
                                        <template slot-scope="scope">
                                            <x-input v-model="scope.row.itemName" @input="changeChild"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="费用类型" align="center">
                                        <template slot-scope="scope">
                                            <template v-if="scope.row.costType == '子项合计'">{{scope.row.costType}}
                                            </template>
                                            <template v-else-if="scope.row.idxArr&&scope.row.idxArr.length==3">
                                                <x-input v-model="scope.row.costType"></x-input>
                                            </template>
                                            <el-popover placement="bottom" width="50" trigger="hover"
                                                        style="opacity: 0" v-else>
                                                <div class="el-popover_item">
                                                    <el-button type="button" @click="addChild(scope.row,scope.$index)">
                                                        添加子项
                                                    </el-button>
                                                </div>
                                                <div slot="reference">
                                                    <x-input v-model="scope.row.costType"></x-input>
                                                </div>
                                            </el-popover>

                                        </template>
                                    </el-table-column>
                                    <el-table-column label="对内合同金额（元）" align="center">
                                        <template slot-scope="scope">
                                            <x-input v-model="scope.row.internalContractAmount" @input="sum"
                                                     type="number"
                                                     min="0"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="对外合同金额（元）" align="center">
                                        <template slot-scope="scope">
                                            <x-input v-model="scope.row.externalContractAmount" @input="sum"
                                                     type="number"
                                                     min="0"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="前期已录金额（元）" align="center">
                                        <template slot-scope="scope">
                                            <x-input v-model="scope.row.earlyAmountRecorded" @input="sum" type="number"
                                                     min="0"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="开累已录金额（元）" align="center" prop="kaileiAmountRecorded">
                                    </el-table-column>
                                    <el-table-column label="对外合同剩余金额（元）" align="center" prop="externalResidualAmount">
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div class="title">
                            <h3>费用清单信息</h3>
                        </div>
                        <el-row>
                            <x-col>
                                <el-form-item label="合同总价">
                                    <span>{{info.contractTotalPrice}}</span>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <div class="unit">
                            <div class="unit_add">
                                <button class="layui-btn layuiadmin-btn-admin" type="button" data-type="add"
                                        @click="addExpenseInvoiceList">
                                    添加
                                </button>
                            </div>
                            <div class="unit_center">
                                <div class="unit_img">
                                    <div class="item" v-for="(item,index) in expenseInvoiceList" :key="index"
                                         v-if="expenseInvoiceList.length>1">
                                        <img src="${ctx}/resources/images/del.png" alt=""
                                             @click="delExpenseInvoiceList(index)">
                                    </div>
                                </div>
                                <el-table :data="expenseInvoiceList" style="width: 100%" border>
                                    <el-table-column label="清单名称" align="center">
                                        <template slot-scope="scope">
                                            <x-input name="清单名称" v-model="scope.row.namesList"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="计量单位" align="center">
                                        <template slot-scope="scope">
                                            <x-input name="计量单位" v-model="scope.row.unitMeasurement"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="合同数量" align="center">
                                        <template slot-scope="scope">
                                            <x-input name="合同数量" v-model="scope.row.contractQuantity" type="number"
                                                     min="0" @input="expenseInvoiceListSum"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="合同单价" align="center">
                                        <template slot-scope="scope">
                                            <x-input name="合同单价" v-model="scope.row.contractPrice" type="number"
                                                     min="0" @input="expenseInvoiceListSum"></x-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="summation" label="合计" align="center"></el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div class="title">
                            <h3>合同信息</h3>
                        </div>
                        <el-row>
                            <x-col>
                                <el-form-item label="合同工期(年)">
                                    <x-input name="合同工期" v-model="info.contractDurationYear" type="number"
                                             min="0"></x-input>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="合同工期(天)">
                                    {{info.contractDurationYear?info.contractDurationYear*365:0}}
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="合同开工日期">
                                    <el-date-picker style="width: 100%" type="date" value-format="yyyy-MM-dd"
                                                    v-model="info.commencementDate"
                                                    placeholder="合同开工日期"></el-date-picker>
                                </el-form-item>
                            </x-col>
                            <x-col position="right">
                                <el-form-item label="合同竣工日期">

                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col>
                                <el-form-item label="合同结算模式">
                                    <x-select name="合同结算模式" v-model="info.contractSettlementMode"
                                              :options="settlementPatternEnumList"></x-select>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <el-row>
                            <x-col position="full">
                                <el-form-item label="乙方完成标准">
                                    <x-input type="textarea" :rows="4" v-model="info.completionCriteria"></x-input>
                                </el-form-item>
                            </x-col>
                        </el-row>
                        <div class="title">
                            <h3>项目附件信息</h3>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">Word版合同文本</label>
                            <div class="layui-input-block">
                                <div class="layui-upload">
                                    <button type="button" class="layui-btn" type="button" id="107-upload-more">上传
                                    </button>
                                    <div class="layui-upload-list" id="107-upload-more-list">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">PDF版合同文本</label>
                            <div class="layui-input-block">
                                <div class="layui-upload">
                                    <button type="button" class="layui-btn" type="button" id="108-upload-more">上传
                                    </button>
                                    <div class="layui-upload-list" id="108-upload-more-list">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">政府发函</label>
                            <div class="layui-input-block">
                                <div class="layui-upload">
                                    <button type="button" class="layui-btn" type="button" id="109-upload-more">上传
                                    </button>
                                    <div class="layui-upload-list" id="109-upload-more-list">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">其他附件</label>
                            <div class="layui-input-block">
                                <div class="layui-upload">
                                    <button type="button" class="layui-btn" type="button" id="110-upload-more">上传
                                    </button>
                                    <div class="layui-upload-list" id="110-upload-more-list">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-form>
                </div>
            </div>
            <%--<div class="layui-tab-item">
                <%@ include file="process/process-history.jsp" %>
            </div>--%>
        </div>
    </div>
</div>
<script src="${ctx}/resources/vue-element-lib/jquery.js"></script>
<script>
    // 封装上传文件
    let fileArr = [];

    var staticPath = '${fileHttpPre}';
    layui.config({
        base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'set', 'upload', 'table', 'transfer', 'laydate', 'element', 'layer'], function () {
        var $ = layui.$
            , upload = layui.upload
            , table = layui.table
            , element = layui.element
            , layer = layui.layer;

        //选项卡切换监听
        element.on('tab(xqxx-tab-all)', function (data) {
            var layId = $(this).attr('lay-id');
            vm.$data.layId = layId
            if (layId === "0") {

            } else if (layId === "1") {
                loadTable(layId);
            } else if (layId === "2") {

            }
        });

        function loadTable(layId) {
            // 表单
            table.render({
                elem: '#lay-lsspxx-create-manage'
                , url: basePath + '/historyProcess/list?proCode=${proCode}'
                , cols: [[
                    {
                        field: 'startTime', title: '发起时间', width: 145, width: 155, templet: function (d) {
                            return layui.util.toDateString(d.startTime, "yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    , {field: 'startRealName', title: '发起人', width: 145}
                    , {field: 'proFlowType', title: '审批阶段', width: 145}
                    , {
                        field: 'dealTime', title: '审批日期', width: 155, templet: function (d) {
                            return layui.util.toDateString(d.dealTime, "yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    , {field: 'dealName', title: '审批人', width: 160}
                    , {
                        field: 'state', title: '审批状态'
                    }
                    , {
                        title: '操作', width: 140, align: 'center', fixed: 'right', templet: function (d) {
                            var optStr = "";
                            optStr += '<a class="layui-btn layui-btn-xs" lay-event="view"><i class="layui-icon layui-icon-form"></i>查看</a>';
                            return optStr;
                        }
                    }
                ]]
                , page: true
                , limit: 10
            });

            // 监听操作列
            table.on('tool(lay-lsspxx-create-manage)', function (obj) {
                var data = obj.data;
                if (obj.event === 'view') {//查看
                    parent.layui.index.openTabsPage(basePath + '/historyProcess/toDetail?processId=' + data.processId, '历史流程信息 > 详情');
                }
            });
        }
        ;(function () {
            //定义构造函数
            var Upfile = function (ele, type, opt) {
                this.defaults = {
                    //elem:‘#uploadPic‘	//绑定元素
                    elem: $(ele)	//绑定元素
                    , url: basePath + '/contractInfo/uploadAtt/',
                    data: {
                        types: type
                    },
                    multiple: true,
                    accept: 'file',
                    acceptMime: 'application/zip,application/x-rar-compressed,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf',

                    method: 'post',
                    before: function (obj) { //obj参数包含的信息
                        layer.load(); //上传loading
                    },
                    done: function (res) {
                        //如果上传失败
                        if (res.code > 0) {
                            layer.closeAll('loading'); //关闭loading
                            return layer.msg(res.msg, {icon: 7});
                        }
                        //上传完毕
                        if (res.entity != null && res.entity.length > 0) {
                            fileArr.push(res.entity[0])
                            for (var i in res.entity) {
                                var contractInfo = res.entity[i];
                                var arr = contractInfo.split("|");
                                var imgSrc = "";
                                var suffix = arr[1].substring(arr[1].lastIndexOf(".") + 1, arr[1].length);
                                if (suffix == 'jpg' || suffix == 'png') {
                                    imgSrc = "${fileHttpPre}/" + arr[3];
                                } else {
                                    imgSrc = "${ctx}/resources/images/" + suffix + ".jpg";
                                }
                                $('#' + type + '-upload-more-list')
                                    .append('<div class="layui-upload-img-div" id="upload_img_' + arr[2] + '"><img src="' + imgSrc + '" title="'
                                        + arr[1] + '" class="layui-upload-img"><div class="mask"><a href="javascript:void(0)" onclick="showImg(\'' + "${fileHttpPre}"
                                        + arr[3] + '\');">查看</a><a href="javascript:void(0)" onclick="del(\''
                                        + arr[2] + '\')";>删除</a></div><p>' + arr[1] + '</p><input type="hidden" value="'
                                        + contractInfo + '" id="fileAtt_' + arr[2] + '" name="fileAtts" ></input></div> ');
                            }
                        }
                    },
                    allDone: function (obj) { //当文件全部被提交后，才触发
                        layer.closeAll('loading'); //关闭loading
                    },
                    error: function () {
                        layer.closeAll('loading'); //关闭loading
                        //上传失败
                        layer.msg("上传失败，请稍后再试~", {icon: 7});
                    }
                }
                this.options = $.extend({}, this.defaults, opt);
            };

            //定义方法
            Upfile.prototype = {
                init: function () {
                    var _this = this;
                    return layui.use('upload', function () {
                        var upload = layui.upload;

                        //执行实例
                        var uploadInst = upload.render(_this.options);
                    });
                }
            };

            //在插件中使用对象
            $.fn.upfile = function (options) {
                var upfile = new Upfile(this, options);
                return upfile.init();
            }
        })();
        //上传文件
        $('#107-upload-more').upfile(107);
        $('#108-upload-more').upfile(108);
        $('#109-upload-more').upfile(109);
        $('#110-upload-more').upfile(110);

    });

    //删除文件
    function del(index) {
        layui.$("#fileAtt_" + index).remove();
        layui.$("#upload_img_" + index).remove();
        fileArr.map((el, idx) => {
            if (el.split('|')[2] == index) {
                fileArr.splice(idx, 1)
            }
        })
    }

    //根据url查看文件
    function showImg(url) {
        var openWin = window.open(url, '', 'left=410,height=768, width=1024, top=200,  toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
    }

    /*核心*/
    var vm = new Vue({
        el: '#app',
        data() {
            return {
                layId: 0,
                id: '',
                list: [],
                basic: {},
                info: {},//合同评审信息
                expenseInvoiceList: [],//费用清单信息
                projectAgencyPaymentList: [],//项目代付费信息
                costTypesEnumList: [],//费用类型
                settlementPatternEnumList: [],//合同结算方式
                companyList: [],//公司下拉列表
                projectAgencyPaymentList: [{
                    itemName: '子项名称', costType: '子项合计', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 1, idx: '0',
                }, {
                    itemName: '子项名称', costType: '1建安工程费用', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 1, idx: '1',
                }, {
                    itemName: '子项名称', costType: '2设备购置费用', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 1, idx: '2',
                }, {
                    itemName: '子项名称', costType: '3工程建设其他', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 1,
                    idx: '3', isChild: 1,
                }, {
                    itemName: '子项名称', costType: '3.1征地拆迁费', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 1, idx: '3-1',
                }, {
                    itemName: '子项名称', costType: '4预备费', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 1, idx: '4',
                }, {
                    itemName: '子项名称', costType: '5建设期利息', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 1, idx: '5',
                }],
            }
        },
        created() {
            this.id = "${id}";
            this.costTypesEnum();
            this.settlementPatternEnum();
            this.queryById();
            this.companyNameDropDownBox();
        },

        watch: {
            projectAgencyPaymentList: {
                // 数据处理函数，可以在此处设置从哪一行开始合并
                // 此函数只处理了行合并情况，可根据需求自行设置列处理
                handler(newData) {
                    if (newData.length) {
                        // 标记首行开始合并
                        let mergeStartRow = newData[0]
                        mergeStartRow.isStartMerge = true // 标记开始合并的行
                        mergeStartRow.rowspan = 1 // 标记需要合并行数
                        mergeStartRow.startIndex = 0 // 用于计算合并行数
                        // 需要计算最后一次的合并行数，故需要循环到length次
                        for (let i = 1; i <= newData.length; i++) {
                            // row中itemType字段不相等，则开启下一个合并处理；及最后一次合并
                            if ((newData[i] && mergeStartRow.itemType !== newData[i].itemType) || i === newData.length) {
                                mergeStartRow.endIndex = i // 用于计算合并行数
                                mergeStartRow.rowspan = mergeStartRow.endIndex - mergeStartRow.startIndex // 计算合并行数
                                mergeStartRow = newData[i] // 标记新的合并
                                if (mergeStartRow) {
                                    mergeStartRow.isStartMerge = true
                                    mergeStartRow.rowspan = 1
                                    mergeStartRow.startIndex = i
                                }
                            }
                        }
                    }
                },
                immediate: true
            }
        },
        mounted() {

        },
        methods: {
            companyNameDropDownBox() {
                zAjax('/contractsReview/companyNameDropDownBox', {types: 9}).then(res => {
                    this.companyList = res
                })
            },
            //获取详情
            queryById() {
                zAjax('/contractsReplenish/queryById', {id: this.id}).then(res => {
                    if (res.basic) this.basic = res.basic;
                    if (res.otherContractsReplenish) this.info = res.otherContractsReplenish;
                    if (res.expenseInvoiceList && res.expenseInvoiceList.length > 0) this.expenseInvoiceList = res.expenseInvoiceList;
                    if (res.projectAgencyPaymentList && res.projectAgencyPaymentList.length > 0) this.projectAgencyPaymentList = res.projectAgencyPaymentList;
                    showFile(res.fileAtt)
                    this.expenseInvoiceListSum()
                })
            },
            // 页面费用类型下拉框
            costTypesEnum() {
                zAjax('/contractsReview/costTypesEnum', {}).then(res => {
                    this.costTypesEnumList = res
                })
            },
            //添加费用清单信息
            addExpenseInvoiceList() {
                let obj = {
                    namesList: '',// 清单名称
                    unitMeasurement: '',// 计量单位
                    contractQuantity: '',// 合同数量
                    contractPrice: '',// 合同单价
                    summation: '',//合计
                }
                this.expenseInvoiceList.push(obj)
            },
            //删除费用清单信息
            delExpenseInvoiceList(index) {
                this.expenseInvoiceList.splice(index, 1)
            },
            expenseInvoiceListSum() {
                this.expenseInvoiceList.map(el => {
                    el.summation = (Number(el.contractQuantity) * Number(el.contractPrice)).toFixed(2);
                })
                let sum = 0;
                this.expenseInvoiceList.map(el => {
                    sum += Number(el.summation)
                })
                this.info.contractTotalPrice = sum.toFixed(2)
            },

            // 添加合同清单信息子项
            add() {
                let arr = [{
                    itemName: '子项名称', costType: '子项合计', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 0, idx: '0',
                }, {
                    itemName: '子项名称', costType: '1建安工程费用', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 0, idx: '1',
                }, {
                    itemName: '子项名称', costType: '2设备购置费用', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 0, idx: '2',
                }, {
                    itemName: '子项名称', costType: '3工程建设其他', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 0,
                    idx: '3', isChild: 1,
                }, {
                    itemName: '子项名称', costType: '3.1征地拆迁费', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 0, idx: '3-1',
                }, {
                    itemName: '子项名称', costType: '4预备费', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 0, idx: '4',
                }, {
                    itemName: '子项名称', costType: '5建设期利息', internalContractAmount: 0, externalContractAmount: 0,
                    earlyAmountRecorded: 0, kaileiAmountRecorded: 0, externalResidualAmount: 0, itemType: 0, idx: '5',
                }];
                let itemType = this.projectAgencyPaymentList[this.projectAgencyPaymentList.length - 1].itemType;
                arr.map(el => {
                    el.itemName = el.itemName + (Number(itemType) + 1);
                    el.itemType = Number(itemType) + 1;
                    el.add = true;//以这个字段来代表是否是新增
                })
                this.projectAgencyPaymentList = this.projectAgencyPaymentList.concat(arr);
                this.$nextTick(() => {
                    // 初始化表格
                    this.$refs.tableRef.doLayout();
                })
            },
            //删除子项
            del(itemType) {
                for (let i = this.projectAgencyPaymentList.length; i >= 0; i--) {
                    if (this.projectAgencyPaymentList[i]) {
                        if (this.projectAgencyPaymentList[i].itemType == itemType) {
                            this.projectAgencyPaymentList.splice(i, 1)
                        }
                    }
                }
            },
            // 添加合同清单信息子节点
            addChild(e, index) {
                //把父项的 isChild = true
                this.projectAgencyPaymentList.map(el => {
                    if (el.itemType == e.itemType && el.idx == e.idx) {
                        el.isChild = 1;
                    }
                })
                let arr = [];
                console.log(e)
                this.projectAgencyPaymentList.map(el => {
                    if (el.itemType == e.itemType) {
                        console.log(e.idxArr);
                        console.log(el.parent);
                        if (JSON.stringify(e.idxArr) == JSON.stringify(el.parent)) {
                            arr.push(el.idxArr[el.idxArr.length - 1])
                        }
                    }
                });
                arr.sort((a, b) => {
                        return b - a
                    }
                );
                let obj = {
                    itemName: e.itemName,
                    costType: e.idx + '-' + (Number(arr[0] ? arr[0] : 0) + 1),
                    externalBeginAmount: 0,
                    externalFloat: 0,
                    externalAfterAmount: 0,
                    internalFloat: 0,
                    itemType: e.itemType,
                    idx: e.idx + '-' + (Number(arr[0] ? arr[0] : 0) + 1)
                }
                this.projectAgencyPaymentList.splice(index + 1, 0, obj);
                this.sum();
                console.log(this.projectAgencyPaymentList)
            },
            changeChild(e) {

            },
            //合同清单信息计算
            sum() {
                //internalContractAmount  对内合同金额
                //externalContractAmount 对外合同金额
                //earlyAmountRecorded 前期已录金额
                //kaileiAmountRecorded 开累已录金额
                //externalResidualAmount 对外合同剩余金额
                let arr = total(this.projectAgencyPaymentList, 'itemType');
                arr.map(item => {
                    item.map(el => {
                        if (el.idx) {
                            el.idxArr = el.idx.split("-")
                        }
                        if (el.idxArr && el.idxArr.length == 3) {
                            el.parent = [el.idxArr[0], el.idxArr[1]]
                        }
                        if (el.idxArr && el.idxArr.length == 2) {
                            el.parent = [el.idxArr[0]]
                        }
                        if (el.idxArr && el.idxArr.length == 1) {
                            if (el.idxArr[0] != 0) {
                                el.parent = [0]
                            }
                        }
                    })
                    // extBeginAmountBack internalAmount
                    item.map(el => {
                        if (el.isChild == 1) {
                            el.internalContractAmount = 0;
                            el.externalContractAmount = 0;
                            el.earlyAmountRecorded = 0;
                        }
                    });
                    for (let k = 3; k >= 1; k--) {
                        for (let i = 0; i < item.length; i++) {
                            for (let j = 0; j < item.length; j++) {
                                if (item[i] && item[j]) {
                                    if (JSON.stringify(item[i].idxArr) == JSON.stringify(item[j].parent)) {
                                        if (item[j].idxArr.length == k) {
                                            item[i].internalContractAmount += Number(item[j].internalContractAmount);
                                            item[i].externalContractAmount += Number(item[j].externalContractAmount);
                                            item[i].earlyAmountRecorded += Number(item[j].earlyAmountRecorded);

                                        }
                                    }
                                }
                            }
                        }
                    }

                    //计算合计金额
                    let internalContractAmount = 0;
                    let externalContractAmount = 0;
                    let earlyAmountRecorded = 0;
                    let kaileiAmountRecorded = 0;
                    item.map(el => {
                        if (el.parent && el.parent[0] == 0) {
                            internalContractAmount += Number(el.internalContractAmount);
                            externalContractAmount += Number(el.externalContractAmount);
                            earlyAmountRecorded += Number(el.earlyAmountRecorded);
                        }
                    });
                    item.map(el => {
                        if (el.idx == 0) {
                            el.internalContractAmount = internalContractAmount;
                            el.externalContractAmount = externalContractAmount;
                            el.earlyAmountRecorded = earlyAmountRecorded;

                        }
                        el.internalContractAmount = el.internalContractAmount ? el.internalContractAmount : 0;
                        el.externalContractAmount = el.externalContractAmount ? el.externalContractAmount : 0;
                        el.earlyAmountRecorded = el.earlyAmountRecorded ? el.earlyAmountRecorded : 0;

                        //开累已录金额 =  前期已录金额+对内合同金额
                        el.kaileiAmountRecorded = Number(el.internalContractAmount) + Number(el.earlyAmountRecorded);
                        el.kaileiAmountRecorded = el.kaileiAmountRecorded ? el.kaileiAmountRecorded.toFixed(2) : 0

                        //对外合同剩余金额  = 对外合同金额 - 开累已录金额
                        el.externalResidualAmount = Number(el.externalContractAmount) - Number(el.earlyAmountRecorded);
                        el.externalResidualAmount = el.externalResidualAmount ? el.externalResidualAmount.toFixed(2) : 0

                    })
                })
                this.projectAgencyPaymentList = flatten(arr)
            },

            objectSpanMethod({row, column, rowIndex, columnIndex}) {
                if (columnIndex === 0) {
                    if (row.rowspan) {
                        return {
                            rowspan: row.rowspan,
                            colspan: 1
                        };
                    } else {
                        return {
                            rowspan: 0,
                            colspan: 0
                        };
                    }
                }
            },
            // 页面合同结算方式下拉框
            settlementPatternEnum() {
                zAjax('/contractsReview/settlementPatternEnum', {}).then(res => {
                    this.settlementPatternEnumList = res
                })
            },
            error(text) {
                this.$message({
                    message: text,
                    type: 'warning'
                });
            },
            //保存
            save(type) {
                let obj = {
                    basic: this.basic,
                    otherContractsReplenish: this.info,//项目基础信息
                    expenseInvoiceList: this.expenseInvoiceList,//费用清单信息
                    projectAgencyPaymentList: this.projectAgencyPaymentList,//项目代付费信息
                    fileAtt: fileArr
                }
                let str = JSON.stringify(obj).replace(/\"/g, '\\"');
                zAjax('/contractsReplenish/save', {
                    bodyStr: str,
                    submitType: type + ''
                }).then(res => {
                    if (res.success) {
                        this.$message({
                            message: '提交成功',
                            type: 'success'
                        });
                    } else {
                        this.$message.error(res.msg);
                    }
                })

            },
        }
    })
</script>
</body>
</html>

